from pathlib import Path
import hashlib
import time
import uuid
import random
import json
import sys
import os

# 简化导入方式
try:
    # 先尝试直接导入
    from com.request_interceptor import RequestInterceptor
except ImportError:
    # 如果直接导入失败，尝试使用相对导入
    from ..com.request_interceptor import RequestInterceptor

class BaseApi:
    """API基类，包含所有接口通用的属性和方法"""
    BASE_URL = "https://api.youpin898.com"
    
    def __init__(self, device_token, device_id, auth_token, uk=""):
        """初始化API基类
        
        Args:
            device_token: 设备令牌
            device_id: 设备ID
            auth_token: 授权令牌
            uk: uk值
        """
        self.device_token = device_token
        self.device_id = device_id
        self.authorization = auth_token
        self.uk = uk
        self.interceptor = RequestInterceptor()
        self._request_tag = None  # 缓存requesttag
        
    def generate_request_tag(self, device_id: str = None) -> str:
        """生成请求标签
        
        Args:
            device_id: 设备ID，如果不传则使用实例的device_id
            
        Returns:
            str: 请求标签
        """
        if not device_id:
            device_id = self.device_id
            
        if not self._request_tag:
            self._request_tag = hashlib.md5(
                f"{device_id}{int(time.time() * 1000)}".encode()
            ).hexdigest().upper()
        return self._request_tag

    @property
    def common_headers(self):
        """返回通用请求头"""
        # 生成或获取requesttag
        request_tag = self.generate_request_tag()
        
        # 为 device-info 生成不同的 requestTag
        device_info_request_tag = hashlib.md5(
            f"{self.device_id}{int(time.time() * 1000) - 1000}".encode()
        ).hexdigest().upper()
        
        # 创建设备信息字符串
        device_info = json.dumps({
            "deviceId": self.device_id or "",
            "deviceType": ApiConfig.DEVICE_TYPE,
            "hasSteamApp": 0,
            "requestTag": device_info_request_tag,
            "systemName": ApiConfig.SYSTEM_NAME,  
            "systemVersion": ApiConfig.SYSTEM_VERSION
        })
        
        # 基础请求头
        headers = {
            "host": "api.youpin898.com",
            "tracestate": ApiConfig.TRACE_STATE,
            "traceparent": ApiConfig.generate_trace_parent(),
            "requesttag": request_tag,
            "gameid": ApiConfig.GAME_ID,
            "devicetype": "6",
            "platform": "android",
            "currenttheme": "Light",
            "package-type": "uuyp",
            "content-encoding": "gzip",
            "app-version": ApiConfig.APP_VERSION,
            "content-type": "application/json; charset=utf-8",
            "accept-encoding": "gzip",
            "user-agent": ApiConfig.USER_AGENT,
            "apptype": "4"  
        }
        
        # 添加可选字段
        if self.device_token:
            headers["devicetoken"] = self.device_token
        
        if self.device_id:
            headers["deviceid"] = self.device_id
            
        if self.uk:
            headers["uk"] = self.uk
            
        if self.authorization:
            headers["authorization"] = self.authorization
            
        # 添加设备信息
        headers["device-info"] = device_info
        
        return headers

class ApiConfig:
    """API配置信息"""
    # 应用和系统版本
    APP_VERSION = "5.29.2"
    DEVICE_TYPE = "RMX3122"
    SYSTEM_NAME = "Android"
    SYSTEM_VERSION = "11"
    USER_AGENT = "okhttp/3.14.9"
    GAME_ID = "730"  # CS:GO 的游戏ID
    TRACE_STATE = f"bnro=android/{SYSTEM_VERSION}_android/8.12.1_okhttp/3.14.9"
    
    # 设备基本信息（从真实设备获取）
    MANUFACTURER = "realme"
    BRAND = "realme"
    MOD_TIME = 1710212910000
    CPU_COUNT = 8
    CPU_ABI = "arm64-v8a"
    CPU_ABI2 = ""
    CPU_MAX = "2000000"
    SCREEN = "720*1536"
    DPI = 320
    DEVICE_OS_BUILD = "RP1A.200720.011"
    TIMEZONE = "Asia/Shanghai"
    LOCATION = "CN"
    LANGUAGE = "zh"
    FINGERPRINT = "realme/RMX3122/RMX3122CN:11/RP1A.200720.011/1710215975881:user/release-keys"
    PACKAGE = "com.uu898.uuhavequality"
    APP_NAME = "com.stub.StubApp"
    VERSION_CODE = 2025030707
    LVC = 0
    MAC = ""  # 真实设备MAC地址为空（Android 10+保护隐私）
    AID = "d72fe7cc28264af0"  # Android ID
    FILE_SIZE = 78262521
    
    # 内存和存储（从真实设备获取）
    MEM_MIN = 22469104
    MEM_MAX = 22469104
    FMEM_MIN = 0
    FMEM_MAX = 0
    FD_MIN = 86007468032
    FD_MAX = 86007468032
    DS_SIZE = 115207012352
    
    # 时间戳（从真实设备获取）
    BOOT_TIME = 1743193671497
    INSTALL_TIME = 1743159065424
    UPDATE_TIME = 1743159065424
    
    # CPU信息（从真实设备获取）
    CPU_INFO = """processor\t: 0
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x2
CPU part\t: 0xd05
CPU revision\t: 0

processor\t: 1
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x2
CPU part\t: 0xd05
CPU revision\t: 0

processor\t: 2
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x2
CPU part\t: 0xd05
CPU revision\t: 0

processor\t: 3
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x2
CPU part\t: 0xd05
CPU revision\t: 0

processor\t: 4
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x2
CPU part\t: 0xd05
CPU revision\t: 0

processor\t: 5
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x2
CPU part\t: 0xd05
CPU revision\t: 0

processor\t: 6
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x4
CPU part\t: 0xd0b
CPU revision\t: 0

processor\t: 7
BogoMIPS\t: 26.00
Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
CPU implementer\t: 0x41
CPU architecture: 8
CPU variant\t: 0x4
CPU part\t: 0xd0b
CPU revision\t: 0

Hardware\t: MT6833V/ZA"""

    @staticmethod
    def generate_trace_parent() -> str:
        """生成跟踪父ID
        
        Returns:
            str: 格式为 "00-[32位hex]-[16位hex]-01" 的跟踪ID
        """
        return f"00-{uuid.uuid4().hex}-{uuid.uuid4().hex[:16]}-01"
    
    @staticmethod
    def generate_memory_info() -> tuple:
        """生成内存相关信息
        
        Returns:
            tuple: (mems, fmem, fd) 的元组
        """
        return (
            random.randint(ApiConfig.MEM_MIN, ApiConfig.MEM_MAX),
            random.randint(ApiConfig.FMEM_MIN, ApiConfig.FMEM_MAX),
            random.randint(ApiConfig.FD_MIN, ApiConfig.FD_MAX)
        )

    @staticmethod
    def generate_device_info(device_id: str, request_tag: str) -> str:
        """生成标准化的设备信息JSON"""
        return json.dumps({
            "deviceId": device_id,
            "deviceType": ApiConfig.DEVICE_TYPE,
            "hasSteamApp": 0,  # 修正为整数类型
            "requestTag": request_tag,
            "systemName": ApiConfig.SYSTEM_NAME,
            "systemVersion": ApiConfig.SYSTEM_VERSION
        }, ensure_ascii=False)

    @staticmethod
    def generate_device_data() -> dict:
        """生成设备数据
        
        Returns:
            dict: 设备数据字典
        """
        mems, fmem, fd = ApiConfig.generate_memory_info()
        boot_time = ApiConfig.BOOT_TIME
        # 随机在最后一位加1或保持不变
        if random.random() < 0.5:
            boot_time += 1
            
        return {
            "manu": ApiConfig.MANUFACTURER,
            "brand": ApiConfig.BRAND,
            "mod": ApiConfig.MOD_TIME,
            "cpucnt": ApiConfig.CPU_COUNT,
            "abi": ApiConfig.CPU_ABI,
            "abi2": ApiConfig.CPU_ABI2,
            "cpuinfos": ApiConfig.CPU_INFO,
            "cpumax": ApiConfig.CPU_MAX,
            "mems": mems,
            "fmem": fmem,
            "fd": fd,
            "ds": ApiConfig.DS_SIZE,
            "scr": ApiConfig.SCREEN,
            "dpi": ApiConfig.DPI,
            "type": "Phone",
            "os": ApiConfig.SYSTEM_NAME,
            "osvn": ApiConfig.SYSTEM_VERSION,
            "osvc": 30,  # 修改为30，与真实请求一致
            "osb": ApiConfig.DEVICE_OS_BUILD,
            "tz": ApiConfig.TIMEZONE,
            "loc": ApiConfig.LOCATION,
            "lang": ApiConfig.LANGUAGE,
            "fp": ApiConfig.FINGERPRINT,
            "bootT": boot_time,
            "font": 1,
            "pkg": ApiConfig.PACKAGE,
            "lvc": ApiConfig.LVC,
            "vc": ApiConfig.VERSION_CODE,
            "vn": ApiConfig.APP_VERSION,
            "dn": ApiConfig.APP_NAME,
            "it": ApiConfig.INSTALL_TIME,
            "ut": ApiConfig.UPDATE_TIME,
            "u": False,  # 修改为False，与真实请求一致
            "sn": "-998, Attempt to invoke virtual method 'android.content.pm.Signature[] android.content.pm.SigningInfo.getApkContentsSigners()' on a null object reference",
            "len": ApiConfig.FILE_SIZE,
            "aid": ApiConfig.AID,
            "fs": f"/data/user/0/{ApiConfig.PACKAGE}/files",
            "imeis": "-999",
            "phone": "-999",
            "mac": ApiConfig.MAC,
            "bt": True,
            "mob": True,
            "av": True,
            "con": True,
            "r": False  # 修改为False，与真实请求一致
        }
